<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/5/8
 * Time: 下午2:48
 */

namespace App\Busi\Modules\Resource;


use App\Busi\Modules\BaseBusi;
use App\Busi\Traits\CompanyCaseTrait;
use App\Busi\Traits\CompanyTrait;
use App\Busi\Traits\UserTrait;
use App\Exceptions\ErrorCode\UserError;
use App\Exceptions\UserException;
use App\Http\Requests\CompanyCaseAddRo;
use App\Models\CompanyCase;

class CompanyCaseAddBusi extends BaseBusi
{
    use UserTrait,CompanyTrait,CompanyCaseTrait;
    public function handle(CompanyCaseAddRo $ro){
        $id = $ro->id;
        $uid = $ro->uid;
        $poster = $ro->poster;
        $img_host = config("admin.upload.host");
        $host_count = strlen($img_host);
        $poster = substr($poster,$host_count,strlen($poster)-$host_count);
        $company_name = $ro->company_name;
        $category_id = $ro->category_id;
        $service_desc = $ro->service_desc;
        $project_cycle = $ro->project_cycle;
        $project_price = $ro->project_price;
        $staff = $ro->staff;
        $is_hidden = $ro->is_hidden;
        $user = $this->getUserByUid($uid);
        if(!$user){
            throw new UserException(UserError::USER_NOT_EXIST);
        }
        $raw_company = $this->getCompanyByUid($uid);
        if(!$raw_company){
            throw new UserException(UserError::USER_NOT_AUTH);
        }
        $company_id = $raw_company['id'];
        //如果存在id,则是编辑案例信息
        if($id){
            $raw_company_case = $this->getCaseByIdAndCompanyId($id,$company_id);
            if($raw_company_case){
                $update = [
                    "poster"=>$poster,
                    "company_name"=>$company_name,
                    "category_id"=>$category_id,
                    "service_desc"=>$service_desc,
                    "project_cycle"=>$project_cycle,
                    "project_price"=>$project_price,
                    "staff"=>$staff,
                    "is_hidden"=>$is_hidden,
                ];
                CompanyCase::where("id",$id)->update($update);
                $data = [
                    "msg" =>"更新成功"
                ];
                return $data;
            }
            else{
                //如果没找到 就更新失败
                throw new UserException(UserError::USERID_NOT_EXSIT_OR_NOT_AUTH);
            }
        }
        else{
            //如果没有传id 添加案例
            $raw_companycase = CompanyCase::create([
                'company_id'=>$company_id,
                'poster'=>$poster,
                "company_name"=>$company_name,
                "category_id"=>$category_id,
                "service_desc"=>$service_desc,
                "project_cycle"=>$project_cycle,
                "project_price"=>$project_price,
                "staff"=>$staff,
                "is_hidden"=>$is_hidden,
            ]);

            $data = [
                'msg'=>"上传成功"
            ];
            return $data;

        }



    }


}